import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'

export class JsonStore<T extends object> {
  constructor(private file: string, private defaults: T) {
    if (!existsSync(file)) {
      mkdirSync(dirname(file), { recursive: true })
      writeFileSync(file, JSON.stringify(defaults, null, 2))
    }
  }
  load(): T {
    try {
      return JSON.parse(readFileSync(this.file, 'utf-8')) as T
    } catch {
      return this.defaults
    }
  }
  save(data: T) {
    writeFileSync(this.file, JSON.stringify(data, null, 2))
  }
}

